package com.stone.sys.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import com.stone.para.IConstant;
import com.stone.sys.pojo.TOrgan;
import com.stone.sys.pojo.TUser;
import com.stone.sys.service.OrganService;
import com.stone.sys.service.UserService;
import com.stone.utils.JsonUtils;
import com.stone.utils.Resources;

import frm.ssh.action.BaseAction;
import frm.ssh.exception.AppException;
import frm.ssh.util.SpringUtil;

/**
 * 登陆用ACTION
 * 
 * <pre>
 * @author：JZ
 * @since:2010/02/10
 * </pre>
 */
public class LoginAction extends BaseAction {

	private UserService userService;
	private String loginId;
	private String password;
	private String err = "";
	// 父节点
	private String parentID;
	
	/**
	 * 登录验证
	 */
	public String login() throws AppException {

		TUser user = null;

		List<HashMap<String, Object>> list = userService.getListByDHql(" u as u", "loginId = ?", new Object[]{loginId}, "", "TUser u");

		if (list.size() == 0) {
			this.err = "没有此用户";
		} else {
			user = (TUser) ((HashMap<String, Object>)list.get(0)).get("u");
			if (!password.equals(user.getPassword())) {
				this.err = "用户密码错误";
			}
			
			if ("0".equals(user.getState()) && !"1".equals(user.getIsadmin())) {
				this.err = "该用户已停用";
			}
		}

		if (!err.equals("")) {
			
			userList  = this.userService.getListByDHql("u.loginId as loginId, u.name as name", 
					"",
					null, 
					" order by u.id", 
					"TUser u");
			
			return "LOGIN_ERROR";
		} else {
			
			// 是否管理员（1是,0不是）
			this.setSessionAttribute(IConstant.SESSION_ISADMIN, user.getIsadmin());

			// 用户信息放入SESSION
			this.setSessionAttribute(IConstant.SESSION_TUSER, user);
			
			// 角色串
			String sql = "Select Substr(Sys_Connect_By_Path(NAMEEN, ','), 2) as v " + 
			  "From (Select Rownum Rid, Rownum + 1 Next_Rid, NAMEEN " + 
			          "From sys_role " + 
			         "where id in (select role_id from sys_user_role where user_id = '" + user.getId() + "')) " + 
			 "Where Rid = " + 
			       "(Select Count(*) " + 
			          "From sys_role " + 
			         "where id in (select role_id from sys_user_role where user_id = '" + user.getId() + "')) " + 
			 "Start With Rid = 1 " + 
			 "Connect By Prior Next_Rid = Rid ";

			String roles = "";
			List<HashMap<String, Object>> l = userService.findListBySql(sql);

			if (l.size() > 0) {

				roles = l.get(0).get("v").toString() + ",";
			} else {
				roles = "";
			}
			
			if ("1".equals(user.getIsadmin())) {
				roles += "isadmin,";
			}
			
			// 角色传放入SESSION
			this.setSessionAttribute(IConstant.SESSION_ROLES, roles);
			
			// 机构信息
			if (user.getOrgan().getId() != 0) {
	
				TOrgan organ = (TOrgan)this.userService.findById(user.getOrgan().getId(), TOrgan.class.getName());
				
				if (organ != null && organ.getOrganCode() != null) {
					
					this.setSessionAttribute(IConstant.SESSION_TORGAN, organ);
					this.setSessionAttribute(IConstant.SESSION_TORGAN_CODE, organ.getOrganCode());
					this.setSessionAttribute(IConstant.SESSION_ISCITY, organ.getOrganCode().toString().length() == 9 ? "0" : "1");
					
				} else  {
					this.err = "该用户没有上级部门，没有权限查询";
					return "LOGIN_ERROR";
				}
			} else {
				
				this.setSessionAttribute(IConstant.SESSION_TORGAN_CODE,Long.parseLong("101"));
			}

			return SUCCESS;
		}
	}
	
	/**
	 * 查询登陆用户权限对应的菜单
	 * @return
	 * @throws AppException
	 */	
	@SuppressWarnings("unchecked")
	public void getMenuByUserRole() throws IOException, AppException {
		
		List<HashMap<String,Object>> listTree = null;
		
		// 如果是超级管理员具有全部权限
		if ("1".equals(this.getSessionAttribute(IConstant.SESSION_ISADMIN))) {
			
			listTree = userService.getListByDHql(
					"m.id as id, m.title as text, m.qtip as qtip,m.url as url,m.parentID as parentID," +
					"(case when (select count(tm.id) from TMenu tm where tm.parentID = m.id and tm.btnId is null)> 0 then false else true end) as leaf", 
					"m.parentID = ? and m.btnId is null ",
					new Object[]{Long.parseLong(parentID)}, 
					"order by m.parentID,m.sortId",
					"TMenu m");
		} else {
		
			listTree  = userService.getListByDHql(
					"m.id as id, m.title as text, m.qtip as qtip,m.url as url,m.parentID as parentID," +
					"(case when (select count(tm.id) from TMenu tm where tm.parentID = m.id and tm.btnId is null)> 0 then false else true end) as leaf", 
					"u.id = ur.userId and ur.roleId = rm.roleId and rm.menuId = m.id and m.parentID = ? and u.id = ? and m.btnId is null ",
					new Object[]{Long.parseLong(parentID),((TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER)).getId()}, 
					" group by m.id,m.title,m.url,m.qtip,m.parentID,m.sortId order by m.parentID,m.sortId",
					" TUser u, TUserRole ur, TRoleMenu rm ,TMenu m");
			}
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
        JSON json = JSONSerializer.toJSON(listTree, jsonConfig);
        super.getResponse().getWriter().print(json.toString());
        
	}

	/**
	 * 登陆页面的下拉框
	 * 
	 * @return
	 * @throws AppException
	 */
	@SuppressWarnings("unchecked")
	public String beforeLogin() throws Exception {

		userList  = this.userService.getListByDHql("u.loginId as loginId, u.name as name", 
																				"",
																				null, 
																				" order by u.sortid", 
																				"TUser u");
		return "LOGIN_ERROR";
		
	}
	
	private List<HashMap<String,Object>> userList;
	
	private List<HashMap<String,Object>> deptList;
	
	public List<HashMap<String, Object>> getUserList() {
		return userList;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getLoginId() {
		return loginId;
	}

	public void setLoginId(String loginId) {
		this.loginId = loginId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getErr() {
		return err;
	}

	public String getParentID() {
		return parentID;
	}

	public void setParentID(String parentID) {
		this.parentID = parentID;
	}

	public void setErr(String err) {
		this.err = err;
	}

	public List<HashMap<String, Object>> getDeptList() {
		return deptList;
	}
	
	
	
}
